<template>
  <a-modal :title="title" :width="1000" v-model:visible="visible" @ok="onSubmit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
      <a-row>
        <a-col v-for="(i, idx) in appform" :key="idx + 'b'" :span="14">
          <a-form-item :label="i.label" :name="i.name">
            <a-input v-if="i.type === 'input' && i.name !== 'secret'" v-model:value="i.value" @change="valueChange" />
            <a-radio-group v-if="i.type === 'radio'" v-model:value="i.value" button-style="solid">
              <a-radio-button v-for="(e, num) in i.options" :value="e.value">{{ e.label }}</a-radio-button>
            </a-radio-group>
            <a-select
              v-if="i.type === 'select'"
              v-model:value="i.value"
              :mode="i.mode || ''"
              @change="i.change($event, i.name)"
              :options="i.options"
            ></a-select>
            <a-textarea v-if="i.type === 'textarea'" v-model:value="i.value" :auto-size="{ minRows: 2, maxRows: 5 }" />
            <a-switch v-if="i.type === 'switch'" v-model:checked="i.value" :checkedValue="1" :unCheckedValue="0">
              <template #checkedChildren><check-outlined /></template>
              <template #unCheckedChildren><close-outlined /></template>
            </a-switch>
            <UploadImg v-if="i.type === 'img'" v-model:value="i.value"></UploadImg>
            <UploadFile v-if="i.type === 'upFile'" v-model:value="i.value" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, nextTick, reactive, toRaw, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import _ from 'lodash';
import UploadImg from '/@/components/file/img.vue';
import UploadFile from '/@/components/file/uploadFile.vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { applicationManagementApi } from '/@/api/system/applicationManagement-api';
import { configureApi } from '../../../../api/system/configure-api.js';

// 基本信息form
const appform = ref([
  { label: '字段名', name: 'attr', value: '', type: 'input', options: [], disabled: false },
  { label: '名称', name: 'attrName', value: '', type: 'input', options: [], disabled: false },
  {
    label: '数据类型',
    name: 'type',
    value: 'varchar',
    type: 'select',
    options: [
      { label: '字符型', value: 'varchar' },
      { label: '数值型', value: 'int' },
      { label: '布尔型', value: 'boolean' },
    ],
    disabled: false,
  },
  { label: '默认值', name: 'defaultValue', value: '', type: 'input', options: [], disabled: false },
  {
    label: '扩展对象',
    name: 'resources',
    value: 'user',
    type: 'select',
    options: [
      { label: '用户', value: 'user' },
      { label: '组织机构', value: 'org' },
    ],
    disabled: false,
  },
  { label: '排序', name: 'sortIndex', value: '1', type: 'input', options: [], disabled: false },
  { label: '描述', name: 'description', value: '', type: 'textarea', options: [], disabled: false },
]);

const activeKey = ref(0);
// emit
const emit = defineEmits(['reload']);

// 组件ref
const formRef = ref();

const formDefault = {
  id: undefined,
};
let form = reactive({ ...formDefault });
const rules = {
  attr: [{ required: true, message: '请输入字段名', trigger: 'blur' }],
  attrName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
};
// 是否展示抽屉
const visible = ref(false);
const formType = ref(null);
const title = ref('');

function showDrawer(rowData, index, type) {
  title.value = type;
  formType.value = index;
  if (index) {
    //添加
    onClose();
  } else {
    //编辑
    appform.value.forEach((i) => {
      i.value = rowData[i.name] || '';
      form[i.name] = i.value;
    });
    Object.assign(form, rowData);
  }
  console.log(form);
  
  visible.value = true;
}

//添加之前清空
function onClose() {
  appform.value.forEach((i) => {
    i.value = i.defaultValue || '';
    //清空之后给默认值
    switch (i.name) {
      case 'sortIndex':
        i.value = 1;
        break;
      case 'resources':
        i.value = 'user';
        break;
        break;
      case 'type':
        i.value = 'varchar';
        break;
    }
  });
  visible.value = false;
}

const paramObj = {};

function valueChange() {
  Object.assign(paramObj);

  paramObj['switch_status'] = true;
  // paramObj['status'] = 1;

  appform.value.forEach((i) => {
    if (i.name === 'select_authorizedGrantTypes' && i.value && i.value.length) {
      paramObj['authorizedGrantTypes'] = i.value.join(',');
    } else if (i.name === 'select_scope' && i.value && i.value.length) {
      paramObj['scope'] = i.value.join(',');
    } else {
      paramObj[i.name] = i.value;
    }
  });
  Object.assign(form, paramObj);
}

async function onSubmit() {
  valueChange();

  console.log(form);
  formRef.value
    .validate()
    .then(async () => {
      // SmartLoading.show();
      try {

        let res;
        //1 新增  0编辑
        if (formType.value == 1) {
          res = await configureApi.addExpandattrs(paramObj);
        } else {
          res = await configureApi.expandattrsUpdate(form);
        }

        message.success(`${form.id ? '修改' : '添加'}成功`);
        onClose();
        emit('reload');
      } catch (error) {
        smartSentry.captureError(error);
      } finally {
        // SmartLoading.hide();
      }
    })
    .catch((error) => {
      console.log('error', error);
      message.error('参数验证错误，请仔细填写表单数据!');
    });
}
onMounted(() => {});
defineExpose({
  showDrawer,
});
</script>
